window.onload = function () {
    //白板模块加载完成后，再进行PDF模块的加载
    document.getElementById('pdf-content-frame').src = 'lib/pdfjs/web/viewer.html';
};


// 刷新或关闭提示
window.onbeforeunload = function(e){
    console.log(e);
    e.returnValue = '确认要离开或刷新吗？';
    return e.returnValue;
};

canvas = new fabric.Canvas('main-canvas');
canvas.selectionFullyContained = true;
canvas.preserveObjectStacking = true;
renderJson(DocManager.currentDoc.getPage(1).getData());

//启用按钮组单选功能
$('.btn').button();

//启用提示工具
const btns = $("[data-toggle='tooltip']");
btns.tooltip({'trigger':'hover'});
//点击时隐藏提示
btns.click(function () {
    $(this).tooltip('hide');
});

const fragments = $('.fragment');
const toolBtn = $('.tool-btn');
//弹出内容框的切换
toolBtn.click(function () {
    const id = this.getAttribute('data-target');
    fragments.each(function () {
        if(this.id !== id){
            $(this).hide('fast');
        }else if(requireLogin(this)){
            $('#login').modal('show');
        }else {
            $(this).toggle('fast', function(){
				$('.fragment :checked').each(function(idx,elem){
					if(elem.id !== 'shape-fill')
						$(this).parent().click();
					else
						$('#shape-line').parent().click();
				});
			});
        }
    });
});

$('#info-panel-close').click(closeInfo);

//全屏控制
document.getElementById('fullscreen-controller').onclick = function () {
    let method;
    const docElm = document.documentElement;
    if(fullscreenElement()){
        exitFullscreen();
    }else {
        requestFullscreen(docElm);
    }
};


document.getElementById('slide-play').onclick = function () {
    //进入播放
    exitFullscreen();
    setTimeout(function () {
        requestFullscreen(mcanvas);
        mcanvas.onclick = function () {
            $('#next-page').click();
        };
    }, 50);
};

//全屏事件响应
$(document).bind('fullscreenchange mozfullscreenchange webkitfullscreenchange msfullscreenchange', function () {
    const controller = document.getElementById('fullscreen-controller');
    if(fullscreenElement()){
        controller.className = 'icon-resize-small icon-hover';
    }else {
        controller.className = 'icon-resize-full icon-hover';
        mcanvas.onclick = null;
    }
});

//键盘事件
document.onkeydown = function (event) {
    switch (event.keyCode){
        case 46:
            //delete--删除选中的对象
            canvas.getActiveObjects().forEach(function (o) {
                if(o.type === 'i-text' && o.isEditing)
                    return; //正在编辑的文字保持delete默认行为
                canvas.remove(o);
            });
            canvas.renderAll();
            break;
        case 37: //左
        case 38: //上
            $('#prev-page').click();
            break;
        case 39: //右
        case 40: //下
            $('#next-page').click();
            break;
        default:
            break;
    }
};

//需要登录的模块进行登录检查
function requireLogin(fragment) {
    return fragment.getAttribute('data-condition') === 'logged' && !user.logged;
}


$('#page-delete').click(function(){
	bootbox.confirm({
		title: "删除当前页面?",
		message: "注意：删除后无法恢复",
		buttons: {
			confirm: {
				label: '确认',
				className: 'btn-danger'
			},
			cancel: {
				label: '取消',
				className: 'btn-success'
			}
		},
		callback: function (result) {
			if(!result) return;
            let cnum = parseInt(currentPageNumber.text());
            let tnum = parseInt(totalPageNumber.text());
			DocManager.currentDoc.deletePage(cnum, function (success) {
                if(!success){
                    showInfo("删除失败，请稍后重试");
                    return;
                }
                tnum = (tnum !== 1) ? tnum-1 : tnum;
                cnum = (cnum !== 1) ? cnum-1 : cnum;
                renderJson(DocManager.currentDoc.getPage(cnum).getData());
                currentPageNumber.text(cnum);
                totalPageNumber.text(tnum);
            });
		}
	});
});

$('#page-insert').click(function () {
    const num = parseInt(currentPageNumber.text());
    DocManager.currentDoc.getPage(num).saveOnline(function (success) {});
    DocManager.currentDoc.addPage(1+num);
    renderJson(DocManager.currentDoc.getPage(1+num).getData());
    currentPageNumber.text(1+num);
    totalPageNumber.text(1 + parseInt(totalPageNumber.text()));
});

$('#page-export').click(function(){
	const type = 'image/jpeg';
	let imgData = canvas.toDataURL(type);
	const down = document.createElement('a');
	down.href = imgData;
	down.download = 'canvas.jpg';
	down.click();
});

$('#prev-page').click(function () {
    let num = parseInt(currentPageNumber.text());
    if(num === 1)
        return;
    DocManager.currentDoc.getPage(num).saveOnline(function (success) {});
    num = num-1;
    renderJson(DocManager.currentDoc.getPage(num).getData());
    currentPageNumber.text(num);
});

$('#next-page').click(function () {
    const total = parseInt(totalPageNumber.text());
    let num = parseInt(currentPageNumber.text());
    if(num === total){
        if(fullscreenElement() === mcanvas)
            exitFullscreen();
        return;
    }
    DocManager.currentDoc.getPage(num).saveOnline(function (success) {});
    num = num + 1;
    renderJson(DocManager.currentDoc.getPage(num).getData());
    currentPageNumber.text(num);
});


function isValidTel(tel) {
    return parseInt(tel).toString().length === 11;
}

$('#reg-form').submit(function () {
    let regError = $('#reg-error');
    const tel = $('#reg-tel').val(),
        password = $('#reg-psw').val(),
        code = $('#reg-code').val();
    if(!isValidTel(tel)){
        regError.text('手机号码输入有误');
        return false;
    }
    if(password.length === 0){
        regError.text('请输入密码');
        return false;
    }
    if(code.length === 0){
        regError.text('请输入验证码');
        return false;
    }
    user.register(tel, password, code, function (msg, success) {
        if(success){
            regError.text('');
            $('#reg-psw').val('');
            $('#reg-code').val('');
            $('#register').modal('hide');
            showInfo(msg);
            $('#user-tel').text(tel);
        }else {
            regError.text(msg);
        }
    });
    return false;
}).find('input').click(function () {
    $('#reg-error').text('');
});

$('#reset-form').submit(function () {
    let error = $('#reset-error');
    const tel = $('#reset-tel').val(),
        password = $('#reset-psw').val(),
        code = $('#reset-code').val();
    if(!isValidTel(tel)){
        error.text('手机号码输入有误');
        return false;
    }
    if(password.length === 0){
        error.text('请输入密码');
        return false;
    }
    if(code.length === 0){
        error.text('请输入验证码');
        return false;
    }
    user.resetpsw(tel, password, code, function (msg, success) {
        if(success){
            error.text('');
            $('#reset-psw').val('');
            $('#reset-code').val('');
            $('#reset-password').modal('hide');
            showInfo(msg);
            loadUserData();
        }else {
            error.text(msg);
        }
    });
    return false;
}).find('input').click(function () {
    $('#reset-error').text('');
});

$('#login-form').submit(function () {
    let loginError = $('#login-error');
    const tel = $('#login-tel').val(), password = $('#login-psw').val();
    if(!isValidTel(tel)){
        loginError.text('手机号码输入有误');
        return false;
    }
    if(password.length === 0){
        loginError.text('请输入密码');
        return false;
    }
    user.login(tel, password, function (msg, success) {
        if(success){
            loginError.text('');
            $('#login-psw').val('');
            $('#login').modal('hide');
            showInfo(msg);
            loadUserData();
        }else {
            loginError.text(msg);
        }
    });
    //网页不跳转
    return false;
}).find('input').click(function () {
    $('#login-error').text('');
});

$('#reset-psw-btn').click(function () {
    $('#user-fragment').hide('fast');
    $('#reset-password').modal('show');
});

$('#logout-btn').click(function () {
    user.logout(function () {
        renderFirstPage(DocManager.initDoc);
        setFilesTable([]);
        $('#user-fragment').hide('fast');
        changeInfo('您已退出登录，文档将无法保存');
    });
});

$('.sendcode-btn').click(function () {
    let ErrorDiv, telInput;
    if(this.id === 'sendcode-reg'){
        telInput = $('#reg-tel');
        ErrorDiv = $('#reg-error');
    } else {
        telInput = $('#reset-tel');
        ErrorDiv = $('#reset-error');
    }
    const tel = telInput.val();
    if(!isValidTel(tel)){
        ErrorDiv.text('手机号码输入有误');
        return false;
    }
    const btn = $(this);
    btn.attr('disabled','disabled');
    let sec = 60;
    let timer = setInterval(function () {
        sec--;
        btn.text('再次发送(' + sec +')');
        if(sec === 0){
            btn.text('发送验证码');
            btn.removeAttr('disabled');
            clearInterval(timer);
        }
    }, 1000);
    $.ajax({
        type: 'POST',
        url: '/user/sendcode',
        data: {
            tel: tel
        },
        success: function (json) {},
        error: function (o) {
            ErrorDiv.text(getAjaxErrorMsg(o));
            btn.text('发送验证码');
            btn.removeAttr('disabled');
            clearInterval(timer);
        }
    });
});

function loadUserData() {
    if(!user.logged) return;
    $('#user-tel').text(user.tel);
    DocManager.loadMyDocs(function (data, success) {
        if(!success){
            showInfo(data);
        }else {
            setFilesTable(data);
        }
    });
}

loadUserData();

$('#reg-tel').val(user.tel);
$('#login-tel').val(user.tel);
$('#reset-tel').val(user.tel);
